<template>
  <PageWrapper contentFullHeight fixedHeight contentClass="main-box">
    <div class="content-box">
      <a-tabs v-model:activeKey="currentTab">
        <a-tab-pane
          v-for="item in tabData"
          :key="item.classifyId"
          :tab="item.classifyName"
        ></a-tab-pane>
        <template #rightExtra>
          <a-date-picker
          :getPopupContainer="(triggerNode) => triggerNode.parentNode"
            v-model:value="year"
            picker="year"
            @change="handleChangeYear"
            :allowClear="false"
          />
        </template>
      </a-tabs>
      <div class="chart-box">
        <Bar :loading="loading" :chartData="chartData" :title="getTitle" />
      </div>
    </div>
  </PageWrapper>
</template>

<script setup>
  import { getClassifyByPatent } from '@/api/collection/classify'
  import { getDictListByCodeAndName } from '@/api/sys/dict'
  import dayjs, { Dayjs } from 'dayjs'
  import { onMounted, ref, watch, unref, computed } from 'vue'
  import { PageWrapper } from '@/components/Page'
  import Bar from '@/components/Charts/Bar/index.vue'
  import { getWaterCostBudget } from '@/api/power/water/costBudget'

  defineOptions({ name: 'Cost' })

  const tabData = ref([])
  const currentTab = ref()
  const year = ref(dayjs())
  const loading = ref(false)
  const chartData = ref({
    xaxisList: [],
    yaxisList: [],
  })

  onMounted(() => {
    getTabData()
  })
  const getTitle = computed(() => {
    const yearVal = dayjs(year.value).year()
    return `${yearVal}年预算与实际费用对比`
  })

  const handleChangeYear = (val) => {
    year.value = val
  }
  const getTabData = async () => {
    const parentData = await getDictListByCodeAndName({
      code: 'budget_manage',
      itemName: 'air_conditioner',
    })
    const data = await getClassifyByPatent({ parentClassifyId: parentData.itemCode })
    tabData.value = data
    if (data.length > 0) {
      currentTab.value = data[0].classifyId
    }
  }

  watch([() => unref(currentTab), () => unref(year)], () => {
    getChartData()
  })

  const getChartData = () => {
    getWaterCostBudget({
      year: dayjs(year.value).year(),
      classifyId: currentTab.value,
    }).then((res) => {
      loading.value = false
      chartData.value = res
    })
  }
</script>

<style scoped>
  .content-box {
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 8px;
    background: #fff;

    .chart-box {
      flex: 1;
    }
  }
</style>